<?php
declare(strict_types=1);

namespace App\Controller\Api\V1;

use App\Constant\SmsConstant;
use App\Model\ChargeProduct;
use App\Model\LiveChargeOrder;
use App\Model\UserAccount;
use App\Model\UserAccountTransaction;
use App\Model\UsersOpenId;
use App\Model\UsersLive;
use App\Model\LiveuserCashout;
use App\Model\Talk\TalkRecordsGift;
use App\Repository\UserRepository;
use Carbon\Carbon;
use Hyperf\DbConnection\Db;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Hyperf\HttpServer\Annotation\Middleware;
use App\Middleware\JWTAuthMiddleware;
use App\Model\User;
use App\Support\SendEmailCode;
use App\Helper\HashHelper;
use App\Service\UserService;
use App\Service\SmsCodeService;
use Psr\Http\Message\ResponseInterface;
use function _PHPStan_76800bfb5\React\Promise\Stream\first;

/**
 * Class UsersController
 * @Controller(prefix="/api/v1/users")
 * @Middleware(JWTAuthMiddleware::class)
 *
 * @package App\Controller\Api\V1
 */
class UsersController extends CController
{
    /**
     * @var UserService
     */
    private $userService;

    /**
     * @var UserRepository
     */
    private $userRepository;


    public function __construct(UserService $userService, UserRepository $userRepository)
    {
        parent::__construct();

        $this->userService = $userService;
        $this->userRepository = $userRepository;
    }

    /**
     * 修改我的密码
     *
     * @RequestMapping(path="change/password", methods="post")
     *
     * @return ResponseInterface
     */
    public function editPassword(): ResponseInterface
    {
        $params = $this->request->inputs(['old_password', 'new_password']);

        $this->validate($params, [
            'old_password' => 'required',
            'new_password' => 'required|min:6|max:16'
        ]);

        $guard = \Hyperf\Utils\Context::get('guard');
        $user = authJwt($guard)->user();
        $user_id = data_get($user, 'id');

        // 验证密码是否正确
//        if (!HashHelper::check($params['old_password'], $userInfo->password)) {
//            return $this->response->fail('旧密码验证失败！');
//        }

        $isTrue = $this->userService->resetPassword($userInfo->mobile, $params['new_password']);
        if (!$isTrue) {
            return $this->response->fail('密码修改失败！');
        }

        return $this->response->success([], '密码修改成功...');
    }

    /**
     * 更换用户手机号
     *
     * @RequestMapping(path="change/mobile", methods="post")
     *
     * @param SmsCodeService $smsCodeService
     * @return ResponseInterface
     */
    public function editMobile(SmsCodeService $smsCodeService): ResponseInterface
    {
        $params = $this->request->inputs(['mobile', 'password', 'sms_code']);

        $this->validate($params, [
            'mobile' => "required|phone",
            'password' => 'required',
            'sms_code' => 'required|digits:6'
        ]);

        if (!$smsCodeService->check(SmsConstant::SmsChangeAccountChannel, $params['mobile'], (string)$params['sms_code'])) {
            return $this->response->fail('验证码填写错误！');
        }

        if (!HashHelper::check($params['password'], $this->user()->password)) {
            return $this->response->fail('账号密码验证失败！');
        }

//        [$isTrue, ] = $this->userService->changeMobile($this->uid(), $params['mobile']);
//        if (!$isTrue) {
//            return $this->response->fail('手机号更换失败！');
//        }

        $smsCodeService->delCode(SmsConstant::SmsChangeAccountChannel, $params['mobile']);

        return $this->response->success([], '手机号更换成功...');
    }

    /**
     * 用户充值产品
     *
     * @RequestMapping(path="charge-product", methods="get")
     *
     */
    public function chargeProduct(): ResponseInterface
    {
        $r = ChargeProduct::where('status', '=', 200)
            ->get()
            ->toArray();

        return $this->response->success($r);
    }

    /**
     * 用户充值产品
     *
     * @RequestMapping(path="charge-product-ios", methods="get")
     *
     */
    public function chargeProductIos(): ResponseInterface
    {
        $r = [
            ['id' => '60', 'name' => '42步币', 'price' => '6', 'points' => '42'],
            ['id' => '300', 'name' => '210步币', 'price' => '30', 'points' => '210'],
            ['id' => '500', 'name' => '350步币', 'price' => '50', 'points' => '350'],
            ['id' => '980', 'name' => '686步币', 'price' => '98', 'points' => '686'],
            ['id' => '5180', 'name' => '3626步币', 'price' => '518', 'points' => '3626'],
            ['id' => '9980', 'name' => '6986步币', 'price' => '998', 'points' => '6986'],
        ];

        return $this->response->success($r);
    }

    /**
     * 用户充值产品下单
     *
     * @RequestMapping(path="charge", methods="post")
     *
     */
    public function charge(): ResponseInterface
    {
        $params = $this->request->all();

        info('充值参数', $params);
        $this->validate($params, [
            'product_id' => 'required|min:1'
        ]);


        if (data_get($params, 'source', '') == 'IOS') {
            $config = [
                ['id' => '60', 'name' => '42步币', 'price' => '6', 'points' => '42'],
                ['id' => '300', 'name' => '210步币', 'price' => '30', 'points' => '210'],
                ['id' => '500', 'name' => '350步币', 'price' => '50', 'points' => '350'],
                ['id' => '980', 'name' => '686步币', 'price' => '98', 'points' => '686'],
                ['id' => '5180', 'name' => '3626步币', 'price' => '518', 'points' => '3626'],
                ['id' => '9980', 'name' => '6986步币', 'price' => '998', 'points' => '6986'],
            ];
            $p = collect($config)->where('id', $params['product_id'])->first();
            if (empty($p)) {
                throw new \Exception('找不到产品');
            }
        } else {
            $p = ChargeProduct::where('status', '=', 200)
                ->where('id', '=', $params['product_id'])
                ->first();
            if (empty($p)) {
                throw new \Exception('找不到产品');
            }
            $p = $p->toArray();

        }


        $guard = \Hyperf\Utils\Context::get('guard');
        $user = authJwt($guard)->user();
        $user_id = data_get($user, 'id');

        $paymentMethod = data_get($params, 'payment_method', 'wx_mp');
        $price = data_get($p, 'price', '');
        $pName = data_get($p, 'name', '');
        $source = data_get($params, 'source', '');
        //如果是IOS,则修改这个人待支付订单状态为-100
        if (data_get($params, 'source', '') == 'IOS') {
            LiveChargeOrder::where('user_id', $user_id)
                ->where('status', 100)
                ->update(['status' => -100]);
        }
        $o = LiveChargeOrder::create([
            'user_id' => $user_id,
            'price' => $price,
            'points' => data_get($p, 'points', ''),
            'product_id' => data_get($p, 'id', ''),
            'product_name' => $pName,
            'payment_method' => $paymentMethod,
            'status' => 100,
        ])->toArray();


        $option = [
            'ip' => '127.0.0.1',
//            'openid' => data_get($usersOpenId, 'open_id', ''),
            'body' => '充值' . $pName,
            'description' => '充值' . $pName,
            'id' => 'liveo' . Carbon::now()->format('Ymd') . data_get($o, 'id', ''),
            'total' => $price,
            'notify_url' => env('APP_URL') . 'api/v1/system/charge/' . data_get($o, 'id', '') . '/wx-notify',
            //            'redirect_url' => env('APP_URL')."/web/weibu/#/pages/poster/poster?game_id=$game_id&id=$source_id&type=1",
//            'redirect_url' => env('APP_URL') . "/web/weibu/#/pages/user-me/my-registration/detail?game_id=$game_id&id=$source_id&pack_id=",
        ];

        if ($source != 'IOS') {
            if ($paymentMethod == 'wx_mp') {
                $pay = new \App\Service\RockyPayLibrary2();
                $usersOpenId = data_get(UsersOpenId::where('app_id', '=', config('payment.weibujishi.wechat.app_id'))
                    ->where('user_id', '=', $user_id)
                    ->first(), 'open_id', '');
                if (empty($usersOpenId)) {
                    info('没找到openid', [$user_id]);
                    throw new \Exception('出错');
                }
                $option['openid'] = $usersOpenId;
                $payParams = $pay->payment($paymentMethod, $option);
                $o['payInfo'] = $payParams;
            } elseif ($paymentMethod == 'wx_app') {
                $pay = new \App\Service\RockyPayLibrary2(config('payment.weibuapp'));
                $payParams = $pay->payment($paymentMethod, $option);
                $o['payInfo'] = $payParams;
            }
        }


        return $this->response->success($o);
    }


    /**
     * 查余额
     *
     * @RequestMapping(path="account", methods="get")
     *
     */
    public function account(): ResponseInterface
    {
        $params = $this->request->inputs(['game_id']);
        $game_id = data_get($params, 'game_id', 0);
        $guard = \Hyperf\Utils\Context::get('guard');
        $user = authJwt($guard)->user();
        $user_id = data_get($user, 'id');
        $res = [
            'balance' => 0,//余额
            'transit_balance' => 0,//在途余额
            'realname' => false,//是否实名
            'rewardme' => 0,//打赏我的
            'rewardother' => 0,//打赏别人
            'is_join' => false,//是否参赛
        ];
//        $account = Db::table('user_balance')->where('user_id', $user_id)->first();
        $account = Db::table('user_live_accounts')->where('user_id', $user_id)->first();
        $res['balance'] = round(data_get($account, 'balance', 0));//转换成派币
        //实名信息
        $userInfo = UsersLive::where('user_id', $user_id)->first();
        if (data_get($userInfo, 'id_num', '')) {
            $res['realname'] = true;
            //打赏我的
            $res['rewardme'] = TalkRecordsGift::leftJoin('signups', 'talk_records_gift.player_id', '=', 'signups.id')
                //->leftJoin('live_gift','talk_records_gift.gift_id','=','live_gift.id')
                ->where('signups.user_id', $user_id)
                ->where('signups.game_id', $game_id)
                ->orderBy('talk_records_gift.id', 'desc')
                ->sum('talk_records_gift.gift_points');
            $joinGame = Db::table('players')->where('user_id', $user_id)->where('activity_id', $game_id)->first();
            $res['is_join'] = !empty($joinGame);
        }
        //打赏别人
        $res['rewardother'] = TalkRecordsGift::leftJoin('signups', 'talk_records_gift.player_id', '=', 'signups.id')
            //->leftJoin('live_gift','talk_records_gift.gift_id','=','live_gift.id')
            ->where('talk_records_gift.user_id', $user_id)
            ->where('signups.game_id', $game_id)
            ->orderBy('talk_records_gift.id', 'desc')
            ->sum('talk_records_gift.gift_points');
        return $this->response->success($res);
    }



    /**
     * 查余额
     *
     * @RequestMapping(path="account2", methods="get")
     *
     */
    public function account2(): ResponseInterface
    {
        $params = $this->request->inputs(['game_id']);
        $game_id = data_get($params, 'game_id', 0);
        $guard = \Hyperf\Utils\Context::get('guard');
        $user = authJwt($guard)->user();
        $user_id = data_get($user, 'id');
        $res = [
            'balance' => 0,//余额
            'transit_balance' => 0,//在途余额
            'realname' => false,//是否实名
            'rewardme' => 0,//打赏我的
            'rewardother' => 0,//打赏别人
            'is_join' => false,//是否参赛
        ];
        $account = Db::table('user_balance')->where('user_id', $user_id)->first();
//        $account = Db::table('user_live_accounts')->where('user_id', $user_id)->first();
//        $res['balance'] = round(data_get($account, 'balance', 0));//转换成派币
        $res['balance'] = round(data_get($account, 'balance', 0) * 10);//转换成派币
        //实名信息
        $userInfo = UsersLive::where('user_id', $user_id)->first();
        if (data_get($userInfo, 'id_num', '')) {
            $res['realname'] = true;
            //打赏我的
            $res['rewardme'] = TalkRecordsGift::leftJoin('signups', 'talk_records_gift.player_id', '=', 'signups.id')
                //->leftJoin('live_gift','talk_records_gift.gift_id','=','live_gift.id')
                ->where('signups.user_id', $user_id)
                ->where('signups.game_id', $game_id)
                ->orderBy('talk_records_gift.id', 'desc')
                ->sum('talk_records_gift.gift_points');
            $joinGame = Db::table('players')->where('user_id', $user_id)->where('activity_id', $game_id)->first();
            $res['is_join'] = !empty($joinGame);
        }
        //打赏别人
        $res['rewardother'] = TalkRecordsGift::leftJoin('signups', 'talk_records_gift.player_id', '=', 'signups.id')
            //->leftJoin('live_gift','talk_records_gift.gift_id','=','live_gift.id')
            ->where('talk_records_gift.user_id', $user_id)
            ->where('signups.game_id', $game_id)
            ->orderBy('talk_records_gift.id', 'desc')
            ->sum('talk_records_gift.gift_points');
        return $this->response->success($res);
    }

    /**
     * 实名认证
     *
     * @RequestMapping(path="realname", methods="post")
     *
     */
    public function realname()
    {
        $guard = \Hyperf\Utils\Context::get('guard');
        $user = authJwt($guard)->user();
        $user_id = data_get($user, 'id');
        $params = $this->request->inputs(['real_name', 'id_num', 'id_type']);
        $this->validate($params, [
            'id_num' => 'required',
            'id_type' => 'required',
            'real_name' => 'required',
        ]);
        //更新实名信息
        $user = UsersLive::where('user_id', $user_id)->first();
        if (data_get($user, 'id_num')) return $this->response->success(['msg' => '已提交实名信息']);
        $res = $user->update([
            'real_name' => $params['real_name'],
            'id_type' => $params['id_type'],
            'id_num' => $params['id_num'],
        ]);
        if ($res == 0) return $this->response->success(['msg' => '实名认证失败']);
        //实名成功 获取被打赏的总金额并存入账户
        $amount = TalkRecordsGift::leftJoin('signups', 'talk_records_gift.player_id', '=', 'signups.id')
            //->leftJoin('live_gift','talk_records_gift.gift_id','=','live_gift.id')
            ->where('signups.user_id', $user_id)
            ->orderBy('talk_records_gift.id', 'desc')
            ->sum('talk_records_gift.gift_points');
        UserAccount::where('user_id', $user_id)->increment('balance', $amount);
        return $this->response->success(['msg' => '实名认证成功']);
    }


    /**
     * 查余额
     *
     * @RequestMapping(path="account3", methods="get")
     *
     */
    public function account3(): ResponseInterface
    {
        $params = $this->request->inputs(['game_id']);
        $game_id = data_get($params, 'game_id', 0);
        $guard = \Hyperf\Utils\Context::get('guard');
        $user = authJwt($guard)->user();
        $user_id = data_get($user, 'id');
        $res = [
            'balance' => 0,//余额
            'transit_balance' => 0,//在途余额
            'realname' => false,//是否实名
            'rewardme' => 0,//打赏我的
            'rewardother' => 0,//打赏别人
            'is_join' => false,//是否参赛
        ];


        $client = new \GuzzleHttp\Client();

        $r = $client->get(env('SPORT_DOMAIN').'api/pai/reword/balance?user_id='.$user_id)->getBody()->getContents();
        $j = json_decode($r, true);
        $balance = data_get($j, 'data', 0);


//        $account = Db::table('user_balance')->where('user_id', $user_id)->first();
//        $account = Db::table('user_live_accounts')->where('user_id', $user_id)->first();
        $res['balance'] = $balance;//转换成派币
//        $res['balance'] = round(data_get($account, 'balance', 0) * 10);//转换成派币
//        //实名信息
//        $userInfo = UsersLive::where('user_id', $user_id)->first();
//        if (data_get($userInfo, 'id_num', '')) {
//            $res['realname'] = true;
//            //打赏我的
//            $res['rewardme'] = TalkRecordsGift::leftJoin('signups', 'talk_records_gift.player_id', '=', 'signups.id')
//                //->leftJoin('live_gift','talk_records_gift.gift_id','=','live_gift.id')
//                ->where('signups.user_id', $user_id)
//                ->where('signups.game_id', $game_id)
//                ->orderBy('talk_records_gift.id', 'desc')
//                ->sum('talk_records_gift.gift_points');
//            $joinGame = Db::table('players')->where('user_id', $user_id)->where('activity_id', $game_id)->first();
//            $res['is_join'] = !empty($joinGame);
//        }
//        //打赏别人
//        $res['rewardother'] = TalkRecordsGift::leftJoin('signups', 'talk_records_gift.player_id', '=', 'signups.id')
//            //->leftJoin('live_gift','talk_records_gift.gift_id','=','live_gift.id')
//            ->where('talk_records_gift.user_id', $user_id)
//            ->where('signups.game_id', $game_id)
//            ->orderBy('talk_records_gift.id', 'desc')
//            ->sum('talk_records_gift.gift_points');
        return $this->response->success($res);
    }


    /**
     * 我的提现记录,充值记录,打赏我的,我打赏别人的
     *
     * @RequestMapping(path="cash_log", methods="get")
     *
     */
    public function cashLog()
    {
        $guard = \Hyperf\Utils\Context::get('guard');
        $user = authJwt($guard)->user();
        $params = $this->request->inputs(['page', 'page_size']);
        $page = data_get($params, 'page', 1);
        $pageSize = data_get($params, 'page_size', 20);
        $user_id = data_get($user, 'id');
        //提现记录
        $cashLog = LiveuserCashout::where('user_id', $user_id)
            ->orderBy('id', 'desc')
            ->forPage($page, $pageSize)
            ->get(['id', 'amount', 'status', 'created_at'])->toArray();
        foreach ($cashLog as &$item) {
            $item['status_name'] = data_get(LiveuserCashout::$status, $item['status'], '');
        }
        //充值记录
        $chargeOrder = LiveChargeOrder::where('user_id', $user_id)
            ->where('status', 200)
            ->orderBy('id', 'desc')
            ->forPage($page, $pageSize)
            ->get(['price', 'points', 'product_name', 'created_at'])->toArray();

        return $this->response->success([
            'cash_log' => $cashLog,
            'charge_order' => $chargeOrder,
        ]);
    }

    /**
     * 我的提现记录,充值记录,打赏我的,我打赏别人的
     *
     * @RequestMapping(path="my_account_log", methods="get")
     *
     */
    public function myAccountLog()
    {
        $params = $this->request->inputs(['page', 'page_size']);
        $page = data_get($params, 'page', 1);
        $pageSize = data_get($params, 'page_size', 20);
        $guard = \Hyperf\Utils\Context::get('guard');
        $user = authJwt($guard)->user();
        $user_id = data_get($user, 'id');
        $sourceType = [
            'talk_records',//送礼物,收礼物
            'live_user_cash_out',//提现
            'live_charge_order',//充值
        ];
        $list = UserAccountTransaction::where('user_id', $user_id)
            ->whereIn('source_type', $sourceType)
            ->orderBy('id', 'desc')
            ->forPage($page, $pageSize)
            ->get(['activity_name', 'amount as points', 'type', 'source_type', 'label', 'created_at'])->toArray();
        foreach ($list as &$item) {
            if ($item['source_type'] == 'live_charge_order' && $item['type'] == 2) $item['label'] = '充值';
            $item['points'] = round($item['points']);
            if ($item['points'] > 0) {
                $item['points'] = '+' . $item['points'];
            } elseif ($item['points'] == 0) {
                $item['points'] = 0;
            }
            $item['price'] = round($item['points']) / 10;
            if ($item['price'] > 0) {
                $item['price'] = '+' . $item['price'];
            } elseif ($item['points'] == 0) {
                $item['price'] = 0;
            }
            $item['type_name'] = data_get(UserAccountTransaction::$type, $item['type'], '');
        }
        return $this->response->success($list);
    }

    /**
     * 我的打赏,打赏别人
     *
     * @RequestMapping(path="my_reward", methods="get")
     *
     */
    public function myReward()
    {
        $params = $this->request->inputs(['page', 'page_size']);
        $page = data_get($params, 'page', 1);
        $page = ($page) ?: 1;
        $pageSize = data_get($params, 'page_size', 20);
        $pageSize = ($pageSize) ?: 20;
        $game_id = data_get($params, 'game_id', 0);
        $guard = \Hyperf\Utils\Context::get('guard');
        $user = authJwt($guard)->user();
        $user_id = data_get($user, 'id');
        //打赏我的
        $rewards = TalkRecordsGift::leftJoin('signups', 'talk_records_gift.player_id', '=', 'signups.id')
            ->leftJoin('users', 'users.id', '=', 'talk_records_gift.user_id')
            //->leftJoin('live_gift','talk_records_gift.gift_id','=','live_gift.id')
            ->where('talk_records_gift.gift_points', '>', 0)
            ->where('signups.user_id', $user_id);
        if ($game_id) $rewards = $rewards->where('signups.game_id', $game_id);
        $rewards = $rewards->orderBy('talk_records_gift.id', 'desc')
            ->forPage($page, $pageSize)
            ->get(['talk_records_gift.*', 'users.name as user_name'])->toArray();
        $rewardMe = [];
        foreach ($rewards as $reward) {
            $rewardMe[] = [
                'id' => data_get($reward, 'id', ''),
                'content' => '来自-' . data_get($reward, 'user_name', '') . '-打赏的“' . data_get($reward, 'gift_name', '') . '”',
                'price' => data_get($reward, 'gift_price', 0),
                'points' => data_get($reward, 'gift_points', 0),
                'created_at' => data_get($reward, 'created_at')
            ];
        }
        //我打赏别人
        $reward_others = TalkRecordsGift::leftJoin('signups', 'talk_records_gift.player_id', '=', 'signups.id')
            //->leftJoin('live_gift','talk_records_gift.gift_id','=','live_gift.id')
            ->where('talk_records_gift.gift_points', '>', 0)
            ->where('talk_records_gift.user_id', $user_id);
        if ($game_id) $reward_others = $reward_others->where('signups.game_id', $game_id);
        $reward_others = $reward_others->orderBy('talk_records_gift.id', 'desc')
            ->forPage($page, $pageSize)
            ->get(['talk_records_gift.*'])->toArray();
        $rewardOther = [];
        foreach ($reward_others as $other) {
            $rewardOther[] = [
                'id' => data_get($other, 'id', ''),
                'content' => '打赏-' . data_get($other, 'player_name', '') . '-“' . data_get($other, 'gift_name', '') . '”',
                'price' => data_get($other, 'gift_price', 0),
                'points' => data_get($other, 'gift_points', 0),
                'created_at' => data_get($other, 'created_at')
            ];
        }
        return $this->response->success([
            'reward_me' => $rewardMe,
            'reward_other' => $rewardOther,
        ]);
    }


    /**
     * 提现
     *
     * @RequestMapping(path="transfer", methods="post")
     *
     */
    public function transfer()
    {
        $guard = \Hyperf\Utils\Context::get('guard');
        $user = authJwt($guard)->user();
        $user_id = data_get($user, 'id');
        $params = $this->request->inputs(['total']);
        $total = data_get($params, 'total', 1);
        $res = $this->userService->wxTransfer($user_id, 1);
        return $res;
        if (data_get($res, 'return_code', '') == 'SUCCESS') {
            //提现成功 余额减少
            UserAccount::where('user_id', $user_id)->decrement('balance', $total);
            return $this->response->success($res);
        }
        return $this->response->success(['提现失败']);
        /* // ['partner_trade_no' => 'hkwdk01052806', 'openId' => 'o9NoBuLwLmfLUUrUkhAy2FsYzLLQ', 'total' => '12', 'desc' => '号卡网流量费退款',],
         foreach ($a as $k => $v) {
             $option = $v;
 //            print_r($option);continue;
             $rockyPay = new RockyPayLibrary2(config('payment.haokawang'));
 //            print_r($option);continue;
             try {
                 $return = $rockyPay->payment('wx_transfer', $option);
                 info('发钱成功', [$option, $return]);
                 print_r($return);
             } catch (\Exception $e) {
                 error('发钱失败', [$option, $e->getMessage(), $e->getFile(), $e->getLine()]);
             }
 //            exit;
         }*/
    }

    /**
     * 本场比赛消费总数
     *
     * @RequestMapping(path="game/view", methods="get")
     *
     */
    public function gameView()
    {
        $guard = \Hyperf\Utils\Context::get('guard');
        $user = authJwt($guard)->user();
        $user_id = data_get($user, 'id');
        $params = $this->request->inputs(['activity_id']);

        $this->validate($params, [
            'activity_id' => 'required|min:1'
        ]);
        $return = [
            'paid' => 0,
            'icome' => 0,
            'balance' => 0,
        ];

        $zhichu = UserAccountTransaction::where('activity_id', '=', $params['activity_id'])
            ->where('user_id', '=', $user_id)
            ->where('type', '=', 1)
            ->sum('amount');

        $return['paid'] = $zhichu;
        $shouru = UserAccountTransaction::where('activity_id', '=', $params['activity_id'])
            ->where('user_id', '=', $user_id)
            ->where('type', '=', 2)
            ->sum('amount');

        $return['icome'] = $shouru;
        $account = UserAccount::where('user_id', $user_id)->first();
        if (!empty($account)) {
            $account = $account->toArray();
            $return['balance'] = round($account['balance']);
        }
        return $this->response->success($account);


        // ['partner_trade_no' => 'hkwdk01052806', 'openId' => 'o9NoBuLwLmfLUUrUkhAy2FsYzLLQ', 'total' => '12', 'desc' => '号卡网流量费退款',],
        foreach ($a as $k => $v) {
            $option = $v;
//            print_r($option);continue;
            $rockyPay = new RockyPayLibrary2(config('payment.haokawang'));
//            print_r($option);continue;
            try {
                $return = $rockyPay->payment('wx_transfer', $option);
                info('发钱成功', [$option, $return]);
                print_r($return);
            } catch (\Exception $e) {
                error('发钱失败', [$option, $e->getMessage(), $e->getFile(), $e->getLine()]);
            }
//            exit;
        }
    }
}
//
//    /**
//     * 本场比赛消费总数
//     *
//     * @RequestMapping(path="share", methods="get")
//     *
//     */
//    public function appShare()
 